package com.lw.unsafe;

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @author LW
 * @2020/8/19 22:30
 */
//同理  java.util.ConcurrentModificationException并发修改异常
public class SetTest {

    public static void main(String[] args) {
//        Set<String> set = new HashSet<>();
//            Set<String> set = Collections.synchronizedSet(new HashSet<>());//第一种解决方案
        /**HashSet底层  就是new了一个HashMap
         *
         */
        Set<String> set = new CopyOnWriteArraySet<>();//CopyOnWrite  写入时复制
        for (int i = 1; i <= 30; i++) {
            new Thread(()->{
                //HashSet的add底层就是map.put
                set.add(UUID.randomUUID().toString().substring(0,5));
                System.out.println(set);
            },String.valueOf(i)).start();
        }

    }
}


